import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Layout } from 'antd';
import { io, Socket } from 'socket.io-client';
import HistoryList from './components/HistoryList/HistoryList';
import ChatContent from './components/ChatContent/ChatContent';
import DataTable from './components/DataTable/DataTable';
import './KimiChat.scss';

const { Sider, Content } = Layout;

export interface ChatMessage {
    request_id: string;
    content: string;
    timestamp: Date;
    type: 'user' | 'assistant';
    messageType?: 'readonly' | 'action'; // 添加消息分类
    status?: 'pending' | 'accepted' | 'rejected';
    isSync?: boolean; // 标识是否为同步消息
}

export interface ChatSession {
    id: string;
    title: string;
    messages: ChatMessage[];
    tableData: TableData[];
    createdAt: Date;
    updatedAt: Date;
}

export interface TableData {
    id: string;
    name: string;
    value: number;
    category: string;
    status: string;
    date: string;
}

const KimiChat: React.FC = () => {
    const [sessions, setSessions] = useState<ChatSession[]>([]);
    const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
    const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
    const [pendingResponses, setPendingResponses] = useState<ChatMessage[]>([]);
    const socket = useRef<Socket | null>(null);

    const currentSession = sessions.find(session => session.id === currentSessionId);

    const handleCreateSession = () => {
        const newSession: ChatSession = {
            id: Date.now().toString(),
            title: `新对话 ${sessions.length + 1}`,
            messages: [],
            tableData: [],
            createdAt: new Date(),
            updatedAt: new Date()
        };
        setSessions(prev => [newSession, ...prev]);
        setCurrentSessionId(newSession.id);
    };

    const handleDeleteSession = (sessionId: string) => {
        setSessions(prev => prev.filter(session => session.id !== sessionId));
        if (currentSessionId === sessionId) {
            setCurrentSessionId(null);
        }
    };

    const handleSelectSession = (sessionId: string) => {
        setCurrentSessionId(sessionId);
    };

    // 初始化Socket.IO连接
    const initializeSocket = useCallback(() => {
        if (socket.current) {
            socket.current.disconnect();
        }
        
        socket.current = io('http://localhost:8080');
        
        socket.current.on('connect', () => {
            console.log('Socket.IO连接已建立');
        });
        
        // 处理匹配更新消息
        socket.current.on('match_update', (data) => {
            try {
                console.log('收到匹配更新:', data);
                const assistantMessage: ChatMessage = {
                    request_id: data.request_id?.toString(),
                    content: data.content || JSON.stringify(data),
                    timestamp: new Date(),
                    type: 'assistant',
                    messageType: 'readonly',
                    status: 'accepted',
                    isSync: true
                };
                
                // 非审核请求：直接添加到会话中
                setSessions(prev => prev.map(session => {
                    if (session.id === currentSessionId) {
                        return {
                            ...session,
                            messages: [...session.messages, assistantMessage],
                            updatedAt: new Date()
                        };
                    }
                    return session;
                }));
                console.log('处理匹配更新消息:', assistantMessage.content);
            } catch (error) {
                console.error('处理匹配更新失败:', error);
            }
        });
        
        // 处理匹配完成消息
        socket.current.on('match_complete', (data) => {
            try {
                console.log('收到匹配完成:', data);
                const assistantMessage: ChatMessage = {
                    request_id: data.request_id?.toString(),
                    content: data.content || '匹配完成',
                    timestamp: new Date(),
                    type: 'assistant',
                    messageType: 'readonly',
                    status: 'accepted',
                    isSync: true
                };
                
                setSessions(prev => prev.map(session => {
                    if (session.id === currentSessionId) {
                        return {
                            ...session,
                            messages: [...session.messages, assistantMessage],
                            updatedAt: new Date()
                        };
                    }
                    return session;
                }));
                
                setIsWaitingForResponse(false);
                console.log('匹配完成，停止等待响应');
            } catch (error) {
                console.error('处理匹配完成失败:', error);
            }
        });
        
        // 处理审核请求
        socket.current.on('audit_request', (data) => {
            try {
                console.log('收到审核请求:', data);
                const auditMessage: ChatMessage = {
                    request_id: data.request_id,
                    content: `审核请求：\n原始关键词: ${data.audit_data.original_keywords}\n映射关键词: ${data.audit_data.mapped_keywords}`,
                    timestamp: new Date(),
                    type: 'assistant',
                    messageType: 'action',
                    status: 'pending',
                    isSync: false
                };
                
                // 检查是否已存在相同的审核请求，避免重复添加
                setPendingResponses(prev => {
                    const existingIndex = prev.findIndex(msg => msg.request_id === data.request_id);
                    if (existingIndex >= 0) {
                        // 如果已存在，更新该请求
                        const updated = [...prev];
                        updated[existingIndex] = auditMessage;
                        console.log('更新现有审核请求:', data.request_id);
                        return updated;
                    } else {
                        // 如果不存在，添加新的审核请求
                        console.log('添加新的审核请求:', data.request_id);
                        return [...prev, auditMessage];
                    }
                });
            } catch (error) {
                console.error('处理审核请求失败:', error);
            }
        });
        
        // 处理审核更新
        socket.current.on('audit_update', (data) => {
            try {
                console.log('收到审核更新:', data);
                const updateMessage: ChatMessage = {
                    request_id: Date.now().toString(),
                    content: `审核更新: ${JSON.stringify(data)}`,
                    timestamp: new Date(),
                    type: 'assistant',
                    messageType: 'readonly',
                    status: 'accepted',
                    isSync: true
                };
                
                setSessions(prev => prev.map(session => {
                    if (session.id === currentSessionId) {
                        return {
                            ...session,
                            messages: [...session.messages, updateMessage],
                            updatedAt: new Date()
                        };
                    }
                    return session;
                }));
            } catch (error) {
                console.error('处理审核更新失败:', error);
            }
        });
        
        // 处理表格数据和其他消息
        socket.current.on('message', (data) => {
            try {
                console.log('收到消息:', data);
                // 处理表格数据
                if (data.type === 'data' && data.sessionId) {
                    console.log('收到表格数据:', data);
                    setSessions(prevSessions => prevSessions.map(session => {
                        if (session.id === data.sessionId) {
                            return {
                                ...session,
                                tableData: data.content,
                                updatedAt: new Date()
                            };
                        }
                        return session;
                    }));
                }
            } catch (error) {
                console.error('处理消息失败:', error);
            }
        });
        
        socket.current.on('disconnect', (reason) => {
            console.log('Socket.IO连接已断开:', reason);
        });
        
        socket.current.on('error', (error) => {
            console.error('Socket.IO错误:', error);
        });
        
        socket.current.on('connect_error', (error) => {
            console.error('Socket.IO连接错误:', error);
        });
        
    }, [currentSessionId]);

    useEffect(() => {
        initializeSocket();
        
        return () => {
            if (socket.current) {
                socket.current.disconnect();
            }
        };
    }, [initializeSocket]);
    

    
    // 请求表格数据的函数
    const requestTableData = () => {
        if (socket.current && socket.current.connected && currentSessionId) {
            socket.current.emit('request_data', {
                content: '请求表格数据',
                sessionId: currentSessionId
            });
            console.log('已发送数据请求，会话ID:', currentSessionId);
        }
    };

    const handleSendMessage = (content: string) => {
        if (!currentSessionId || !socket.current || isWaitingForResponse) return;
        
        setIsWaitingForResponse(true);
        setPendingResponses([]);
        
        const userMessage: ChatMessage = {
            request_id: Date.now().toString(),
            content,
            timestamp: new Date(),
            type: 'user',
            messageType: 'readonly',
            status: 'accepted',
            isSync: true
        };
        
        // 添加用户消息到会话
        setSessions(prev => prev.map(session => {
            if (session.id === currentSessionId) {
                return {
                    ...session,
                    messages: [...session.messages, userMessage],
                    updatedAt: new Date()
                };
            }
            return session;
        }));
        
        // 解析用户输入，构造匹配请求体
        try {
            // 尝试解析JSON格式的输入
            const requestData = JSON.parse(content);
            
            // 发送异步匹配请求
            socket.current.emit('start_async_match', {
                main_req: requestData.main_req || content,
                budget: requestData.budget || 5000,
                fans_req: requestData.fans_req || "18-35岁",
                output_req: requestData.output_req || "内容创作",
                other_req: requestData.other_req || ""
            });
            
            console.log('发送异步匹配请求:', requestData);
        } catch (error) {
            // 如果不是JSON格式，使用默认结构
            socket.current.emit('start_async_match', {
                main_req: content,
                budget: 5000,
                fans_req: "18-35岁",
                output_req: "内容创作",
                other_req: ""
            });
            
            console.log('发送异步匹配请求（默认格式）:', content);
        }
    };
    
    const handleAcceptResponse = (messageId: string) => {
        setPendingResponses(prev => {
            const messageToAccept = prev.find(msg => msg.request_id === messageId);
            if (messageToAccept) {
                // 发送审核结果到服务器
                if (socket.current) {
                    socket.current.emit('audit_response', {
                        request_id: messageId,
                        audit_result: {
                            is_approved: true,
                            audit_score: 85,
                            comments: "审核通过",
                            corrected_keywords: "",
                            auditor_id: "user_001",
                            audit_time: new Date().toISOString()
                        }
                    });
                    
                    console.log('发送审核通过结果:', messageId);
                }
                
                const acceptedMessage = { ...messageToAccept, status: 'accepted' as const };
                
                // 添加到当前会话
                setSessions(prevSessions => prevSessions.map(session => {
                    if (session.id === currentSessionId) {
                        return {
                            ...session,
                            messages: [...session.messages, acceptedMessage],
                            updatedAt: new Date()
                        };
                    }
                    return session;
                }));
                
                // 从待处理列表中移除当前处理的消息
                const updatedPending = prev.filter(msg => msg.request_id !== messageId);
                
                // 检查是否还有待处理的审核请求
                const remainingActionMessages = updatedPending.filter(msg => msg.messageType === 'action');
                
                // 如果所有审核消息都已处理，请求数据
                if (remainingActionMessages.length === 0) {
                    console.log('所有审核请求已处理完成，请求表格数据');
                    requestTableData();
                }
                
                return updatedPending;
            }
            return prev;
        });
    };
    
    const handleRejectResponse = (messageId: string) => {
        setPendingResponses(prev => {
            const messageToReject = prev.find(msg => msg.request_id === messageId);
            if (messageToReject) {
                // 发送审核结果到服务器
                if (socket.current) {
                    socket.current.emit('audit_response', {
                        request_id: messageId,
                        audit_result: {
                            is_approved: false,
                            audit_score: 30,
                            comments: "审核不通过",
                            corrected_keywords: "",
                            auditor_id: "user_001",
                            audit_time: new Date().toISOString()
                        }
                    });
                    
                    console.log('发送审核拒绝结果:', messageId);
                }
                
                const rejectedMessage = { ...messageToReject, status: 'rejected' as const };
                
                // 添加拒绝的消息到当前会话（可选，用于显示拒绝记录）
                setSessions(prevSessions => prevSessions.map(session => {
                    if (session.id === currentSessionId) {
                        return {
                            ...session,
                            messages: [...session.messages, {
                                ...rejectedMessage,
                                content: rejectedMessage.content + '\n\n状态：已拒绝'
                            }],
                            updatedAt: new Date()
                        };
                    }
                    return session;
                }));
            }
            
            // 从待处理列表中移除当前处理的消息
            const updatedPending = prev.filter(msg => msg.request_id !== messageId);
            
            // 检查是否还有待处理的审核请求
            const remainingActionMessages = updatedPending.filter(msg => msg.messageType === 'action');
            
            // 如果所有审核消息都已处理，请求数据
            if (remainingActionMessages.length === 0) {
                console.log('所有审核请求已处理完成，请求表格数据');
                requestTableData();
            }
            
            return updatedPending;
        });
    };
    


    return (
        <Layout className="kimi-chat">
            <Sider width={280} theme="light" className="kimi-chat__sidebar">
                <HistoryList
                    sessions={sessions}
                    currentSessionId={currentSessionId}
                    onCreateSession={handleCreateSession}
                    onDeleteSession={handleDeleteSession}
                    onSelectSession={handleSelectSession}
                />
            </Sider>
            <Content className="kimi-chat__main">
                <ChatContent
                    session={currentSession}
                    onSendMessage={handleSendMessage}
                    isWaitingForResponse={isWaitingForResponse}
                    pendingResponses={pendingResponses}
                    onAcceptResponse={handleAcceptResponse}
                    onRejectResponse={handleRejectResponse}
                />
            </Content>
            <Sider width={400} theme="light" className="kimi-chat__data">
                <DataTable 
                    data={currentSession?.tableData || []} 
                    sessionTitle={currentSession?.title}
                />
            </Sider>
        </Layout>
    );
};

export default KimiChat;